import React, { useEffect, useState } from 'react';
import PropTypes from 'prop-types';
import { makeStyles, useTheme } from '@material-ui/core/styles';
import { useMediaQuery, Typography, IconButton } from '@material-ui/core';
import FacebookIcon from '@material-ui/icons/Facebook';
import TwitterIcon from '@material-ui/icons/Twitter';
import InstagramIcon from '@material-ui/icons/Instagram';
import PinterestIcon from '@material-ui/icons/Pinterest';
import MediaView from './MediaView';

const useStyles = makeStyles(theme => ({
  section: {
    marginBottom: theme.spacing(2),
    [theme.breakpoints.up('md')]: {
      marginBottom: theme.spacing(4),
    },
  },
  image: {
    objectFit: 'cover',
    borderRadius: theme.spacing(1),
  },
  socialIcon: {
    borderRadius: 0,
    marginRight: theme.spacing(2),
    color: theme.palette.text.primary,
    background: theme.palette.alternate.main,
    '&:last-child': {
      marginRight: 0,
    },
  },
}));

const Content = props => {
  const { data, className, ...rest } = props;
  const classes = useStyles();

  const theme = useTheme();
  
  const [uMedias, setUpdatedMedias] = useState([]);

  useEffect(() => {
    prepareMedias();
  }, [data]);

  const prepareMedias = () => {
    let tempMedias = {};
    if (!data.medias) return;
    
    for (var i=0; i<data.medias.length; i++) {
      const media = {...data.medias[i]};
      if (tempMedias[media.pos]) {
        if (tempMedias[media.pos].pObjects) {
          tempMedias[media.pos].pObjects.push(media);
        } else {
          tempMedias[media.pos].pObjects = [media];
        }
      } else {
        tempMedias[media.pos] = media;
      }
    }

    let um = [];
    for (const [key, value] of Object.entries(tempMedias)) {
      //console.log(`${key}: ${value}`);
      um.push(value);
    }
    console.log (um);
    setUpdatedMedias(um);
  }

  return (
    <div className={className} {...rest}>
      <div className={classes.section}>
        <Typography component="p" variant="h6" color="textPrimary">
          {data.description}
        </Typography>
      </div>

      {uMedias.map((media, index) => (
        <MediaView key={index} data={media} />
      ))}

      <div>
        <IconButton className={classes.socialIcon}>
          <FacebookIcon />
        </IconButton>
        <IconButton className={classes.socialIcon}>
          <InstagramIcon />
        </IconButton>
        <IconButton className={classes.socialIcon}>
          <TwitterIcon />
        </IconButton>
        <IconButton className={classes.socialIcon}>
          <PinterestIcon />
        </IconButton>
      </div>
    </div>
  );
};

Content.propTypes = {
  /**
   * External classes
   */
  className: PropTypes.string,
  /**
   * data to be rendered
   */
  data: PropTypes.object.isRequired,
};

export default Content;
